package com.liujun.spring4.demo.aop.ioc.base.beans;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;


/**
 * 进行调用测试
 *
 * @author liujun
 * @version 1.0
 * @date 2018-08-13 07:44:00
 */
public class BeanLiftCycle {

  private static void LifeCycleInBeanFactory() {
    Resource res = new ClassPathResource("com/liujun/spring4/demo/aop/ioc/base/beans/car-beans.xml");

    // 装载容器
    BeanFactory bf = new DefaultListableBeanFactory();
    XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader((DefaultListableBeanFactory) bf);
    reader.loadBeanDefinitions(res);

    // 2,向容器中注册MyBeanPostProcess后处理器
    ((ConfigurableBeanFactory) bf).addBeanPostProcessor(new MyBeanPostProcessor());

    // 3,向容器中注册MyInstantiationAwarebeanPostProcessor后处理器
    ((ConfigurableBeanFactory) bf)
        .addBeanPostProcessor(new MyInstantiationAwareBeanPostProcessor());

    // 4，第一次从容器中获取Car,将触发容器实例化该Bean,这将引发Bean生命周期方法的调用
    Car car1 = (Car) bf.getBean("car");

    car1.introduce();
    car1.setColor("红色");

    // 第二次从容器中获取car直接从缓存池中获取
    Car car2 = (Car) bf.getBean("car");

    // 查看car1和car2是否指向同一引用
    System.out.println("car1 == car2:" + (car1 == car2));

    // 关闭容器
    ((DefaultListableBeanFactory) bf).destroySingletons();
  }

  public static void main(String[] args) {
      LifeCycleInBeanFactory();
  }
}
